package com.augrain.microframework.core.util;

import com.augrain.microframework.core.util.collection.MapUtils;
import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * BeanUtils
 *
 * @author biaoy
 * @since 2024/12/30
 */
@Slf4j
public class BeanUtils {

    private BeanUtils() {

    }

    /**
     * 将bean转换为map
     *
     * @param obj 待转换的bean对象
     * @return map
     */
    public static Map<String, Object> bean2Map(Object obj) {
        if (obj == null) {
            return MapUtils.empty();
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Method getter = property.getReadMethod();

                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            log.error("transform bean to map error ", e);
        }
        return map;
    }
}
